import org.apache.commons.io.input.ReversedLinesFileReader;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Stack;

/**
 * @program: PostGirl-panent
 * @description: 文件处理助手
 * @author: Cheng Zhi
 * @create: 2022-10-04 12:38
 **/
public class FileUtils {

    /**
     * 获取文件总行数
     * @param file
     * @return
     */
    public static long getFileLineCount(File file) {

        long lines= 0;
        try {
            lines = Files.lines(Paths.get(file.getPath())).count();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return lines;
    }

    /**
     * 读取指定行到末尾的内容
     * @param file
     * @param lines
     * @return
     */
    public static String readTailContent(File file, long lines) {
        StringBuilder content =new StringBuilder();
        Stack<String> stack = new Stack<String>();
        try {
            ReversedLinesFileReader object = new ReversedLinesFileReader(file);
            long counter = 0L;
            while(counter < lines) {
                // 对读取到的每一行进行压缩
                String gunzip = StringCompressUtils.gzip(object.readLine() + '\n');
                stack.push(gunzip);
                counter ++;
            }
            long size = stack.size();
            for (long i=0; i<size; i++) {
                content.append(stack.pop());
                content.append("'POST_GIRL'");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            stack = null;
        }
        System.out.println("内容压缩后的长度" + content.length());
        return content.toString();
    }

    public static String split(String str, String symbol) {

        String[] split = str.split(symbol);
        StringBuilder sb = new StringBuilder();
        try {
            for (String st : split) {
                sb.append(StringCompressUtils.gunzip(st));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("内容解压后的长度" + sb.length());
        return sb.toString();
    }
}
